const http = require('http');
const fs = require('fs');
const path = require('path');

http.createServer((req, res) => {
    // sse 请求
    if (req.url === '/sse') {
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*'
        });
        let n = 0;
        const timer = setInterval(() => {
            res.write(`data: ${++n}, num: ${ Math.floor(Math.random() * 10000)} \n\n`);   // 注意结尾必须双 \n
            if (n === 500) { clearInterval(timer); res.end(); }
        }, 1000);
        req.on('close', () => clearInterval(timer));
    }

    // 页面请求
    if (req.url === '/' && req.method === 'GET') {
        res.writeHead(200, {
            'Content-Type': 'text/html',
            'Access-Control-Allow-Origin': '*'
        });
        const htmlPath = path.join(__dirname, 'sse_client.html');
        const html = fs.readFileSync(htmlPath, 'utf8');
        res.end(html)
    }
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');